<template>
  <div class="login">
    <van-nav-bar title="登录" @click-left="$router.back()" />
    <div class="zixun">欢迎注册</div>
    <van-form @submit="register">
      <van-field
        left-icon="manager"
        v-model.number="mobile"
        name="手机号"
        label="手机号"
        :rules="rules.mobile"
      />
      <van-field
        left-icon="lock"
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        :rules="rules.password"
      />
      <van-field
        left-icon="lock"
        v-model="repassword"
        type="password"
        name="确认密码"
        label="确认密码"
        :rules="[{ required: true, message: '请确认密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
// 导入发送注册请求的函数
import { registerFn } from '@/api/register'
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Register',
  data() {
    return {
      // 手机号
      mobile: '13155135220',
      // 密码
      password: '123456',
      // 确认密码
      repassword: '123456',
      // 校验规则
      rules: {
        mobile: [{ required: true, message: '手机号不能为空' }],
        password: [{ required: true, message: '密码不能为空' }]
      },
      // 接受注册返回的信息
      res: {}
    }
  },
  methods: {
    // 提交数据
    async register() {
      // 判断两个密码输入的内容需要一致
      if (this.password !== this.repassword) {
        this.$toast.fail('两次输入的密码不一致，请确认您输入的密码')
        return
      }
      // console.log(11)
      // 发送请求
      // 如果注册成功就去登陆页面
      // 注册失败就提示用户重新注册
      try {
        const { data: res } = await registerFn(this.mobile, this.password)
        this.res = res
        this.$router.push('/login')
        this.$toast.success('登陆成功')
      } catch {
        this.$toast.fail(this.res.errmsg)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.zixun {
  text-align: center;
  color: #1989fa;
  padding: 20px 0;
}
.left {
  display: flex;
  justify-content: flex-end;
  a {
    margin-right: 20px;
    font-size: 8px;
  }
}
</style>
